package com.xiaochong.tir.manager.controller;

import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.manager.util.ManagerVersion;
import com.xiaochong.tir.manager.util.ReturnResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import java.util.Map;
import java.util.Set;

/**
 * @Author: WangXing
 * @Description:
 * @CreateDate: 2018/8/24 9:16
 */
@RestController
@RequestMapping(value = ManagerVersion.API_V1_PREFIX+"redis/")
@Api("redis数据查询")
public class RedisController {

    @Autowired
    private RedisServer redisServer;
    @Autowired
    private Environment ev;

    /**
     * 查询redis数据页面
     * @return
     */
    @GetMapping("redisQuery")
    public Object redisQuery(){
        return new ModelAndView("redis/rqPage");
    }

    /**
     * 根据key查询数据
     * @param key
     * @return
     */
    @ApiOperation(value = "根据key模糊查询redis数据",notes = "根据key模糊查询redis数据")
    @PostMapping("datas")
    public Object getDatas(@RequestParam("key")String key){
        String result = redisServer.get(key);
        if(StringUtils.isNotBlank(result)){
            return new ReturnResult<>(0,"成功",result,0);
        }else {
            key += "*";
            Jedis jedis = new Jedis(ev.getProperty("spring.redis.host"),
                    Integer.valueOf(ev.getProperty("spring.redis.port")));
            jedis.auth(ev.getProperty("spring.redis.password"));
            jedis.select(Integer.valueOf(ev.getProperty("spring.redis.database")));//选择数据库
            Set<String> set = jedis.keys(key);
            return new ReturnResult<>(0,"成功",set,0);
        }
    }

}
